import userStateTypes from "./interface";
import RootStateTypes from "@/store/interface";
import { Module } from "vuex";
import { login } from "@/api/data";

const userModule: Module<userStateTypes, RootStateTypes> = {
  namespaced: true, //process.env.NODE_ENV !== "production",
  state: {
    id: 0,
    username: '',
    phone: '',
    userPhoto: '',
    grade: 0,
  },
  mutations: {
    set_username(state: any, newData: string) {
      state.username = newData;
    },
    set_grade(state: any, newData: Number) {
      state.grade = newData;
    },
    set_userInfo(state: any, val: userStateTypes) {
      state.id = val.id;
      state.username = val.username;
      state.phone = val.phone;
      state.userPhoto = val.userPhoto;
      state.grade = val.grade;
      localStorage.setItem('userInfo', JSON.stringify(val))
    }
  },
  actions: {

    // 页面刷新时防止信息丢失可以掉用本地存储获取用户信息
    initUser({ commit }) {
      let user = localStorage.getItem('userInfo');
      if (user) {
        let userInfo: userStateTypes = JSON.parse(user);
        commit('set_userInfo', userInfo);
      }
    },

    // 登录
    login({ commit, state }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          commit('set_userInfo', response);
          resolve(response);
        }).catch(error => {
          reject(error);
        });
      });
    },

    // 登出
    logOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('set_userInfo', {
          id: 0,
          username: '',
          phone: '',
          userPhoto: '',
          grade: 0,
        });
        resolve('');
      });

    },

  }
};
export default userModule;